package com.atguigu.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.StockDetailTo;
import com.atguigu.common.to.mq.StockLockedTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.atguigu.gulimall.ware.entity.WareOrderTaskEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.OrderFeignService;
import com.atguigu.gulimall.ware.feign.ProductFeignService;
import com.atguigu.gulimall.ware.service.WareOrderTaskDetailService;
import com.atguigu.gulimall.ware.service.WareOrderTaskService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.OrderItemVo;
import com.atguigu.gulimall.ware.vo.OrderVo;
import com.atguigu.gulimall.ware.vo.SkuHasStockVo;
import com.atguigu.gulimall.ware.vo.WareSkuLockVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RabbitListener(queues = "stock.release.stock.queue")
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;
    @Autowired
    WareOrderTaskService orderTaskService;
    @Autowired
    OrderFeignService orderFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }



    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }


            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }

    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前库存量
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0);
            return vo;
        }).collect(Collectors.toList());

        return collect;
    }

    //库存解锁场景 1.下订单成功。订单过期没有支付被系统自动取消、被用户手动取消。都要解锁库存
    //2.下单成功，库存锁定成功，业务调用失败，导致订单回滚 时间到了之后自动解锁
    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean lockStock(WareSkuLockVo vo) {
        //保存库存工作单
        //1.按照下单的收获地址。找到一个就近仓库，锁定库存
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(wareOrderTaskEntity);
        //2.找到每个商品在哪仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());
        //2.锁定库存
        Boolean allLock = true;
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStock = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIdS = hasStock.getWareId();

                if(wareIdS==null || wareIdS.size()==0){
                    //没有这个库存
                    throw new NoStockException(skuId);
                }
                //1.如果每一个商品都锁定成功，将当前商品锁定了几件的工作记录发给mq
            //2.锁定失败。前面保存的工作单信息就回滚了。发生出去的消息，即使解锁记录，由于数据库差不到id，所以不用解锁
            //
            for (Long wareId : wareIdS) {
                //成功返回1，否则是0
                Long count =wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count==1){
                    //todo 库存锁定成功 触发锁定逻辑
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null, skuId,
                            "", hasStock.getNum(), wareOrderTaskEntity.getId(), wareId,
                            1);
                    orderTaskDetailService.save(entity);
                    StockLockedTo lockedTo = new StockLockedTo();
                    lockedTo.setId(wareOrderTaskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity,stockDetailTo);
                    //只发id不行 防止回滚找不到数据
                    lockedTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend(
                            "stock-event-exchange",
                            "stock.locked",
                            lockedTo);
                    skuStock = true;
                    break;
                }else {
                    //当前仓库锁失败，重试下一个

                }
            }
        if (skuStock==false){
            //没有这个库存
            throw new NoStockException(skuId);
        }
        }
        //3.肯定全部锁定成功
        return true;

    }

    @Override
    public void unlockStock(StockLockedTo to) {

            System.out.println("解锁库存");
            StockDetailTo detail = to.getDetail();
            Long detailId = detail.getId();
            //解锁
            //1.查询数据库 关于这个订单的锁定库存的信息
            //有  证明库存锁定成功，具体解锁看订单情况 1.没有这个订单。不是解锁库存 2.有这个订单 不是解锁库存
            // 没有：库存锁定失败，回滚了、这种情况无需解锁
            WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
            if(byId!=null){
                //解锁
                Long id = to.getId();
                WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
                String orderSn = taskEntity.getOrderSn();//查询订单号
                R r = orderFeignService.getOrderStatus(orderSn);
                if(r.getCode()==0){
                    //订单数据返回成功
                    OrderVo data = r.getData(new TypeReference<OrderVo>() {
                    });

                    if(data==null ||data.getStatus()==4){
                        //订单被取消才能解锁库存
                        if(byId.getLockStatus()==1){
                            //当前库存工作状态是已经锁定时
                            unlockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                        }
                    }
                    else {
                        //消息拒绝，重新放到队列里面，让别人继续消费
                        throw new RuntimeException("远程服务失败");
                    }
                }else {
                    //无需解锁
                }
            }
        }



    /**
     * 回滚数据库的-库存数据
     */
    @Override
    public void unlockStock(Long skuId, Long wareId, Integer num, Long taskDetailId) {
        wareSkuDao.unlockStock(skuId, wareId, num);

        WareOrderTaskDetailEntity e = new WareOrderTaskDetailEntity();
        e.setId(taskDetailId);
        e.setLockStatus(2); // 1锁定 2解锁 3正常扣减
        orderTaskDetailService.updateById(e);
    }


    @Data
    class SkuWareHasStock{
        private Long skuId;
        private List<Long> wareId;
        private Integer num;
    }
}